import React, { useState, useEffect } from 'react';
import { Button, Modal,Form,Input, message,Select, Upload,InputNumber} from "antd";

const FormItem = Form.Item;

const { TextArea } = Input;
const { Option } = Select;
import { UploadOutlined,PlusOutlined, } from '@ant-design/icons';
import { ProFormUploadButton } from '@ant-design/pro-form';
import {removeSysFile } from '@/services/ant-design-pro/apis';
const { Dragger } = Upload;

const updateBizType = (props) =>{
    const {
        onSubmit:handleUpdate,
        onCanel:handleUpdateModalVisibel,
        updateModalVisible
    }=props;
    const tokent = localStorage.getItem('token');
    const token = tokent == undefined ? '' : tokent;
    const [fileList, setFileList] = useState([]);
    const [archivesValue, setArchivesValue] = useState('');
    const [fromVals,setFormVals]=useState({
        id: props.values.id,
        name:props.values.name,
        sort:props.values.sort,
        img:props.values.img
    })

    useEffect(() => {
      // 将逗号分隔的字符串转换为文件列表
      if (fromVals.img == null) {
        return;
      }
      const archivesMap = fromVals.img.split(',');
      const fileListFromString = archivesMap.map((path, index) => ({
        uid: `-${index}`, // 为每个文件生成一个唯一的uid
        name: path.split('/').pop(), // 提取文件名作为显示名
        url: path, // 文件的URL或路径
        type: 'image/jpeg',
        size: '123459',
        status: 'done', // 文件状态设置为已完成
      }));
      setArchivesValue(fromVals.img);
      setFileList(fileListFromString);
    }, []); // 确保只在组件挂载时运行一次
    

    const handleUpload = async ({ onSuccess, onError, file }) => {
        try {
          const uploadFile = async (file) => {
            const formData = new FormData();
            formData.append('uploadfile', file);
            const response = await fetch('/api/upLoad', {
              method: 'POST',
              body: formData,
              headers: {
                'access-control-allow-origin': '*',
                token: token,
              },
            });
            const newResponse = await response.json();
            if (newResponse && newResponse.data) {
              const path = newResponse.data;
              // 更新archivesValue，包含新上传的文件路径
              setArchivesValue((prevValue) => {
                const paths = prevValue ? prevValue.split(',') : [];
                paths.push(path);
                return paths.join(',');
              });
              onSuccess(path, file);
            } else {
              throw new Error('上传失败或返回的数据格式不正确');
            }
          };
          await uploadFile(file);
        } catch (error) {
          console.error(error);
          onError(error, file);
          message.error('文件上传失败');
        }
      };
    
      const handleChange = ({ fileList: newFileList }) => {
        // 使用beforeUpload来过滤文件
        const filteredFileList = newFileList.filter((file) => beforeUpload(file));
        console.log(archivesValue);
        setFileList(filteredFileList.length > 0 ? filteredFileList : fileList);
      };
    
      const handleRemove = (file) => {
        const index = fileList.indexOf(file);
    
        if (index === -1) {
          console.error('文件不在列表中');
          return;
        }
    
        const paths = archivesValue.split(',');
        const element = paths[index];
        const fileName = element.split('/').pop().split('\\').pop(); // 提取文件名
    
        const removeFile = async () => {
          const hide = message.loading('正在删除');
          try {
            await removeSysFile(fileName);
            hide();
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
    
            setArchivesValue((prevValue) => {
              const paths = archivesValue.split(',');
              if (index !== -1) {
                paths.splice(index, 1);
              }
              if (paths.index !== -1) {
                return paths.join(',');
              } else {
                setArchivesValue(undefined);
              }
            });
            message.success('删除成功');
          } catch(error) {
            console.log(error)
            hide();
            message.error('删除失败');
          }
        };
        removeFile();
      };
    
      const beforeUpload = (file) => {
        // 阻止自动上传，如果需要的话，你可以在这里处理图片上传逻辑
        const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJPGorPNG) {
          message.error('只能上传 JPG 或 PNG 格式图片!');
          return false;
        }
        const isLt10K = file.size < 300 * 1024;
        if (!isLt10K) {
          message.error('图片大小不能超过 300KB!');
          return false;
        }
        return true;
      };



    const formLayout = {
        labelCol: {
            span: 7
        },
        wrapperCol: {
            span: 13
        }
    }

    const [form] = Form.useForm();

    const handleSubmit = async ()=>{
        try{
            const fieldVlas = await form.validateFields();
            setFormVals({ ...fromVals, ...fieldVlas });
            handleUpdate({...fromVals,...fieldVlas})
        }catch(error){
            message.error("配置失败");
        }
    }


    return (
        <Modal
          title="配置轮播图"
          width={740}
          destroyOnClose
          visible={updateModalVisible}
          footer={[
            <Button key="cancel" onClick={()=>{
                handleUpdateModalVisibel(false)
            }}>取消</Button>,
            <Button key="submit" type="primary" onClick={()=>{
                handleSubmit();
            }}>提交</Button>
        ]}
          onCancel={()=>{
              handleUpdateModalVisibel(false)
          }}
        >
            <Form
            {...formLayout}
            form={form}
            initialValues={
                {
                    name:fromVals.name,
                    sort:fromVals.sort,
                    img:fromVals.img
                }
            }
            >
     <FormItem
                  label="名称"
                  name="name"
                  rules={[{
                      required:true,
                      message:'名称是必须项'
                  }]}
                >
                    <Input placeholder="请输入名称"></Input>
                </FormItem>
                <FormItem label="排序值" name="sort">
                <InputNumber   style={{ width: '100%' }}

            placeholder="请输入排序值(值越大越靠前)"
          />
                </FormItem>
                <Form.Item
          label="轮播图"
          name="img"
          initialValue={archivesValue} // 设置初始值
        >
          <Upload
            action="" // 替换为你的实际图片上传接口地址
            listType="picture-card"
            fileList={fileList}
            //onPreview={handlePreview}
            onChange={handleChange}
            beforeUpload={beforeUpload}
            onRemove={handleRemove}
            customRequest={handleUpload}
          >
            {fileList.length < 1 && (
              <div>
                <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </button>

              </div>
            )}
          </Upload>
        </Form.Item>
            </Form>
        </Modal>
    )
}

export default updateBizType;